﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using TyNetCoreBlog.Helpers;
using TyNetCoreBlog.Models.Dto.Blog;
using TyNetCoreBlog.Models.Dto.Tag;
using TyNetCoreBlog.Repository.RepositoryWrapper;
using static TyNetCoreBlog.Helpers.ResponseMsg;

namespace TyNetCoreBlog.Controllers
{
    [Route("api/tags")]
    [EnableCors("any")]
    [ApiController]
    public class TagsController : ControllerBase
    {
        private readonly IRepositoryWrapper _repositoryWrapper;
        private readonly IMapper _mapper;

        public TagsController(IRepositoryWrapper repositoryWrapper, IMapper mapper)
        {
            this._repositoryWrapper = repositoryWrapper ?? throw new ArgumentNullException(nameof(repositoryWrapper));
            this._mapper = mapper ?? throw new ArgumentNullException(nameof(mapper));
        }

        /// <summary>
        /// 获取所有tag（文章数量倒序）
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ActionResult<IEnumerable<TagDto>>> GetTags()
        {
            var ts = await _repositoryWrapper.Tag.GetAllAsync();
            var tagDtoList = _mapper.Map<IEnumerable<TagDto>>(ts).ToList();
            return Ok(new ResponseMsg(ApiStatus.OK, tagDtoList));
        }

        
        /// <summary>
        /// 通过id获取一个tag
        /// </summary>
        /// <param name="tagId"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("{tagId}", Name = nameof(GetOneTag))]
        [ResponseCache(Duration = 3)]
        public async Task<ActionResult<TagDto>> GetOneTag(int tagId)
        {
            var tag = await _repositoryWrapper.Tag.GetByIdAsync(tagId);
            if (tag == null)
            {
                return NotFound(new ResponseMsg(ApiStatus.NotFound));
            }
            var tagDto = _mapper.Map<TagDto>(tag);
            return Ok(new ResponseMsg(ApiStatus.OK, tagDto));
        }


        /// <summary>
        /// 通过tagID获取博客
        /// </summary>
        /// <param name="tagId"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("{tagId}/blogs")]
        [ResponseCache(Duration = 3)]
        public async Task<ActionResult<IEnumerable<BlogDto>>> GetBlogsByTagId(int tagId)
        {
            var blogs = await _repositoryWrapper.Blog.GetBlogByTagIdAsync(tagId);
            var blogDtoList = _mapper.Map<IEnumerable<BlogDto>>(blogs).ToList();
            return Ok(new ResponseMsg(ApiStatus.OK, blogDtoList));
        }
    }
}
